package com.zmx.common.common.utils;

import com.google.common.collect.Maps;
import com.zmx.common.common.invocation.InvocationInfo;
import com.zmx.common.common.invocation.InvocationInfoProxy;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @Description: 线程间上下文信息传递工具
 * @ClassName: InvocationInfoUtil
 * @Author zhaomxr
 * @Date 2021-08-24 15:52
 */
@Slf4j
public class InvocationInfoUtil {

    private final static String FIELDS_MAP_KEY = "fieldsMap";

    private final static String PARAMETERS_MAP_KEY = "parametersMap";

    private final static String EXTEND_ATTRIBUTES = "extendAttributes";

    private static Map allMap = Maps.newHashMapWithExpectedSize(3);


    /**
     * 取当前线程上下文信息
     *
     * @return
     */
    public static Map getInvocationInfo() {
        Map fieldsMap = Maps.newHashMapWithExpectedSize(4);
        fieldsMap.put("userId", InvocationInfoProxy.get().getUserId());
        fieldsMap.put("userName", InvocationInfoProxy.get().getUserName());
        fieldsMap.put("systemId", InvocationInfoProxy.get().getSystemId());
        fieldsMap.put("threadName", InvocationInfoProxy.get().getThreadName());
        allMap.put(FIELDS_MAP_KEY, fieldsMap);

        Map parametersMap = Maps.newHashMapWithExpectedSize(16);
        if (InvocationInfoProxy.get().getParametersMap() != null) {
            parametersMap.putAll(InvocationInfoProxy.get().getParametersMap());
        }
        allMap.put(PARAMETERS_MAP_KEY, parametersMap);

        Map extendAttributesMap = Maps.newHashMapWithExpectedSize(16);
        if (InvocationInfoProxy.get().getExtendAttributes() != null) {
            extendAttributesMap.putAll(InvocationInfoProxy.get().getExtendAttributes());
        }
        allMap.put(EXTEND_ATTRIBUTES, extendAttributesMap);


        return allMap;
    }

    /**
     * 设置当前线程上下文信息
     */
    public static void setInvocationInfo(InvocationInfo invocationInfo) {
        InvocationInfoProxy.set(invocationInfo);
    }

    public static void setUserId(String userId) {
        InvocationInfoProxy.setUserId(userId);
    }

    public static void setUserName(String userName) {
        InvocationInfoProxy.setUserName(userName);
    }
}
